package com.laiat.yamba;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

public class StatusProvider extends ContentProvider {

	private static final String TAG = StatusProvider.class.getSimpleName();

	
	public static final Uri CONTENT_URI = Uri.parse("content://com.laiat.yamba.statusprovider");
	public static final String SINGLE_RECORD_MIME_TYPE = "vnd.android.cursor.item/vnd.laiat.yamba.status";
	public static final String MULTIPLE_RECORDS_MIME_TYPE = "vnd.android.cursor.dir/vnd.laiat.yamba.mstatus";
	
	private StatusData statusData;
	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		long id = this.getId(uri);
		SQLiteDatabase db = statusData.getDbHelper().getWritableDatabase();
		int count = 0;
		try {
			if (id < 0) {
				Log.d(TAG, "delete:  No id found in uri=" + uri);
				count = db.delete(StatusData.TABLE, selection, selectionArgs);
			} else {
				Log.d(TAG, "delete:  Id=" + id + "found in uri=" + uri);
				count = db.delete(StatusData.TABLE, createIdWhereClause(id), null);
			}
		} finally {
			db.close();
		}
		
	    // Notify the Context's ContentResolver of the change
	    getContext().getContentResolver().notifyChange(uri, null);
	    
	    return count;

	}

	public String createIdWhereClause(long id) {
		return StatusData.C_ID + "=" + id;
	}

	@Override
	public String getType(Uri uri) {
		return this.getId(uri) < 0 ? MULTIPLE_RECORDS_MIME_TYPE : SINGLE_RECORD_MIME_TYPE;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = statusData.getDbHelper().getWritableDatabase();
		try {
			long id = db.insertOrThrow(StatusData.TABLE, null, values);
			if (id == -1) {
				Log.d(TAG, "insert:  No id found in uri=" + uri);
				throw new RuntimeException(String.format("%s:  Failed to insert [%s] to [%s] for unknown reasons.", TAG, values, uri));
			} 

			Log.d(TAG, "insert:  Id=" + id + "found in uri=" + uri);
			Uri newUri = ContentUris.withAppendedId(uri, id);
			//Notify the Context's ContentResolver of the change
			getContext().getContentResolver().notifyChange(newUri, null);
			return newUri;

		} finally {
			db.close();
		}
	}

	@Override
	public boolean onCreate() {
		statusData = new StatusData(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		long id = this.getId(uri);
		SQLiteDatabase db = statusData.getDbHelper().getReadableDatabase();
		Cursor cursor = null;
		Log.d(TAG, "query:  project=" + projection + "; select=" + selection + "; " + selectionArgs + "; " + sortOrder);
		if (id < 0) {
			Log.d(TAG, "query:  No id found in uri=" + uri);
			cursor = db.query(StatusData.TABLE, projection, selection, selectionArgs, null, null, sortOrder);
		} else {
			Log.d(TAG, "query:  Id=" + id + "found in uri=" + uri);
			cursor = db.query(StatusData.TABLE, projection, createIdWhereClause(id), null, null, null, null);
		}
		
		Log.d(TAG, "query:  cursor=" + cursor);
		
	    // Notify the context's ContentResolver if the cursor result set changes
		cursor.setNotificationUri(getContext().getContentResolver(), uri);

	    return cursor;

	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		long id = this.getId(uri);
		SQLiteDatabase db = statusData.getDbHelper().getWritableDatabase();
		int count = 0;
		try {
			if (id < 0) {
				Log.d(TAG, "update:  No id found in uri=" + uri);
				count = db.update(StatusData.TABLE, values, selection, selectionArgs);
			} else {
				Log.d(TAG, "update:  Id=" + id + "found in uri=" + uri);
				count = db.update(StatusData.TABLE, values, createIdWhereClause(id), null);
			}
		} finally {
			db.close();
		}
		
	    // Notify the Context's ContentResolver of the change
	    getContext().getContentResolver().notifyChange(uri, null);
	    
	    return count;
	}
	
	private long getId(Uri uri) {
		String lastPathSegment = uri.getLastPathSegment();
		if (lastPathSegment != null) {
			try {
				return Long.parseLong(lastPathSegment);
			} catch (NumberFormatException e) {
				Log.e(TAG, "Error parsing uri to get id", e);
			}
		}
		
		return -1;
	}

}
